package Array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Array
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-11-26  16:53
 * @Description: TODO
 * @Version: 1.0
 */
public class 螺旋遍历二维数组LCR146 {

    public int[] spiralArray(int[][] array) {
        List<Integer> order = new ArrayList<Integer>();
        if (array == null || array.length == 0 || array[0].length == 0) {
            return order.stream().mapToInt(Integer::intValue).toArray();
        }
        // 求解矩阵的行列的值
        int rows = array.length, columns = array[0].length;
        // 表示是否已经访问
        boolean[][] visited = new boolean[rows][columns];
        // 一共有多少元素
        int total = rows * columns;
        // 设置初始位置
        int row = 0, column = 0;
        // 设置4个方向
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

        int directionIndex = 0;

        for (int i = 0; i < total; i++) {
            // 添加元素
            order.add(array[row][column]);
            // 设置为已经访问
            visited[row][column] = true;
            //获取下一位置
            int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
                // 开始转弯，directionInde实现对4取余
                directionIndex = (directionIndex + 1) % 4;
            }
            // 计算的新的行列值
            row += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return order.stream().mapToInt(Integer::intValue).toArray();
    }
}
